#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
/*
以下代码演示 使用weak_ptr解决 多线程访问共享对象的线程安全问题
*/
class A {
public:
    A() {
        std::cout << "A()" << std::endl;
    }
    ~A() {
        std::cout << "~A()" << std::endl;
    }

    void func() {
        std::cout << "do something." << std::endl;
    }
};

#if 0
void foo(A* p) {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    p->func();  // 当子线程执行到此处时，实际上对象*p已经在main线程被释放了，线程不安全
}

int main() {
    A* p = new A();

    std::thread t1(foo, p);
    delete p;

    t1.join();
    return 0;
}
#endif

void bar(std::weak_ptr<A> p) {
    std::shared_ptr<A> p_ = p.lock();
    if (p_) {
        p_->func();
    } else {
        std::cout << "A is destructed." << std::endl;
    }
}

int main() {
    {
        std::shared_ptr<A> p(new A());
        std::thread t1(bar, std::weak_ptr<A>(p));
        t1.detach();
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    std::this_thread::sleep_for(std::chrono::seconds(8));
}
